package com.ruoyi.project.jxy.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ZipUtil;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.project.jxy.domain.FileHistory;
import com.ruoyi.project.jxy.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @ClassName UnZipThread
 * @Description TODO
 * @Author zheng
 * @Date 2020/8/17 16:40
 * @Version 1.0
 **/
public class UnZipThread implements Runnable {
    Logger logger = LoggerFactory.getLogger(UnZipThread.class);
    private String zipPath;
    private int threadNum;
    private FileHistory fileHistory;

    public UnZipThread(String zipPath, int threadNum, FileHistory fileHistory) {
        this.zipPath = zipPath;
        this.threadNum = threadNum;
        this.fileHistory = fileHistory;
    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        File file = ZipUtil.unzip(zipPath);
        String dirPath = file.getAbsolutePath();
        dealTxtAndWav(dirPath);

    }

    //处理 音频和文本类型的数据(识别、合成、图片识别、词典百科)
    //(0,1,4,5)
    private void dealTxtAndWav(String dirPath) {
        //音频文件夹
        String wavPath = "";
        if ("4".equals(fileHistory.getType())) {
            //图片
            wavPath = dirPath + File.separator + "img";
        } else if ("2".equals(fileHistory.getType()) || "3".equals(fileHistory.getType())) {
            wavPath = dirPath + File.separator + "mongol";
        } else {
            wavPath = dirPath + File.separator + "wav";
        }

        //文本文件夹
        String txtPath = dirPath + File.separator + "txt";
        //音频存储路径
        File wavDir = FileUtil.newFile(wavPath);
        File[] wavList = wavDir.listFiles();
        //文本存储路径
        File txtDir = FileUtil.newFile(txtPath);
        File[] txtList = wavDir.listFiles();
        if (wavList == null || txtList == null || wavList.length == 0 || wavList.length != txtList.length) {
            logger.error("文件夹为空");
        } else {
            logger.info("====文件夹内文件个数为=====" + wavList.length);
            if (threadNum > wavList.length) {
                threadNum = wavList.length;
            }
            //每个线程分配任务数
            int step = wavList.length % threadNum == 0 ? wavList.length / threadNum : wavList.length / threadNum + 1;
            ThreadPoolExecutor executor = ThreadUtil.newExecutor(5, 10);
            List<Future> futures = new ArrayList<Future>();
            for (int i = 0; i < threadNum; i++) {
                int startIndex = i * step;
                int endIndex = (i + 1) * step;
                endIndex = endIndex < wavList.length ? endIndex : wavList.length;
                FileInfoThread fileInfoThread = new FileInfoThread(startIndex, endIndex, wavList, txtPath, fileHistory);
                Future future = executor.submit(fileInfoThread);
                futures.add(future);
                if (endIndex >= wavList.length) {
                    break;
                }
            }
            //获取返回值结果
            List dataList = new ArrayList();
            for (int i = 0; i < futures.size(); i++) {
                try {
                    dataList.addAll((Collection) futures.get(i).get());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
            executor.shutdown();

            if (dataList.size() == wavList.length) {
                //成功
                fileHistory.setZipFlag("2");
                //保存数据
                if ("0".equals(fileHistory.getType())) {//识别
                    IAsrRecordService asrRecordService = SpringUtils.getBean(IAsrRecordService.class);
                    asrRecordService.saveBatch(dataList);
                } else if ("1".equals(fileHistory.getType())) {
                    ITtsRecordService ttsRecordService = SpringUtils.getBean(ITtsRecordService.class);
                    ttsRecordService.saveBatch(dataList);
                } else if ("4".equals(fileHistory.getType())) {
                    IImgRecordService iImgRecordService = SpringUtils.getBean(IImgRecordService.class);
                    iImgRecordService.saveBatch(dataList);
                } else if ("5".equals(fileHistory.getType())) {
                    IDictionaryRecordService dictionaryRecordService = SpringUtils.getBean(IDictionaryRecordService.class);
                    dictionaryRecordService.saveBatch(dataList);
                } else if ("2".equals(fileHistory.getType())) {
                    ITalkingDictRecordService talkingDictRecordService = SpringUtils.getBean(ITalkingDictRecordService.class);
                    talkingDictRecordService.saveBatch(dataList);
                } else if ("3".equals(fileHistory.getType())) {
                    IAlignedCorpusRecordService alignedCorpusRecordService = SpringUtils.getBean(IAlignedCorpusRecordService.class);
                    alignedCorpusRecordService.saveBatch(dataList);
                }
            } else {
                //失败
                fileHistory.setZipFlag("3");
            }
            IFileHistoryService fileHistoryService = SpringUtils.getBean(IFileHistoryService.class);
            fileHistoryService.updateById(fileHistory);
        }
    }

    //处理txt 文件
    private void dealTxt(String dirPath) {


        //文本文件夹
        //蒙文
        String txtPath = dirPath + File.separator + "txt";
        String chTxtPath = dirPath + File.separator + "ch_txt";
        //文本存储路径
        File txtDir = FileUtil.newFile(txtPath);
        File chTxtDir = FileUtil.newFile(chTxtPath);
        //英文文件
        File[] txtList = txtDir.listFiles();
        //中文文件
        File[] chTxtList = chTxtDir.listFiles();
        if (txtList == null || txtList.length == 0) {
            logger.info("文件夹为空");
        } else {
            if (threadNum > txtList.length) {
                threadNum = txtList.length;
            }
            //每个线程分配任务数
            int step = txtList.length % threadNum == 0 ? txtList.length / threadNum : txtList.length / threadNum + 1;
            ThreadPoolExecutor executor = ThreadUtil.newExecutor(5, 10);
            List<Future> futures = new ArrayList<Future>();
            for (int i = 0; i < threadNum; i++) {
                int startIndex = i * step;
                int endIndex = (i + 1) * step;
                endIndex = Math.min(endIndex, txtList.length);
                FileInfoThread fileInfoThread = new FileInfoThread(startIndex, endIndex, txtList, txtPath, fileHistory);
                Future future = executor.submit(fileInfoThread);
                futures.add(future);
                if (endIndex >= txtList.length) {
                    break;
                }
            }
            //获取返回值结果
            List dataList = new ArrayList();
            for (int i = 0; i < futures.size(); i++) {
                try {
                    dataList.addAll((Collection) futures.get(i).get());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
            executor.shutdown();

            if (dataList.size() == txtList.length) {
                //成功
                fileHistory.setZipFlag("2");
                //保存数据
                //识别
                if ("2".equals(fileHistory.getType())) {
                    ITalkingDictRecordService talkingDictRecordService = SpringUtils.getBean(ITalkingDictRecordService.class);
                    talkingDictRecordService.saveBatch(dataList);
                } else if ("3".equals(fileHistory.getType())) {
                    IAlignedCorpusRecordService alignedCorpusRecordService = SpringUtils.getBean(IAlignedCorpusRecordService.class);
                    alignedCorpusRecordService.saveBatch(dataList);
                }
            } else {
                //失败
                fileHistory.setZipFlag("3");
            }
            IFileHistoryService fileHistoryService = SpringUtils.getBean(IFileHistoryService.class);
            fileHistoryService.updateById(fileHistory);
        }
    }
}
